#coding=utf-8
import logging
import datetime
# from django.shortcuts import render_to_response
from tools.httpUtil import mako_render as render_to_response
from django.http import HttpResponseRedirect, HttpResponse
from django import forms
from django.views.decorators.csrf import csrf_exempt
from WebBase.settings import logger
from apps.cm.SmManager import SmManager
from tools import DBUtil


class UserForm(forms.Form):
    loginName = forms.CharField()
    password = forms.CharField()


#用户登录
@csrf_exempt # 必须添加这行，说是为了为了避免 Cross Site requestuest Forgeries 攻击
def login(request):
    errors=[]
    result = "success"
    message = u'第一次打开' if not request.session.get('user') else u'重新登录'
    if request.method == "POST":
        loginName = request.POST['txxusr']
        password = request.POST['txxpwd']

        try:
            sql = r"select t.is_lock from Sm_Usermessage t  where t.login_name = '%s'" % loginName
            isLock = DBUtil.executeQuery_one(sql)
            if('1' == isLock[0]):
                message = u"用户锁定无法登录，请联系管理员"
                request.session['message'] = message
                result = "fail"
                return result

            user = SmManager().login(loginName, password)
            if user:
                # //输入密码错误次数清零
                sql = "update Sm_Usermessage t set t.psw_wrong_times = 0  where t.login_name  = '%s'" % loginName
                DBUtil.executeUpdate(sql)

                 # //密码有效期判断
                sql = "SELECT " \
                      "CASE WHEN t1.last_psw_modify_date is null or " \
                      "sysdate - t1.last_psw_modify_date>=t1.psw_valid_days " \
                      "THEN '1' " \
                      "ELSE '0'  " \
                      "END psw_valid_flag  " \
                      "from SM_USERMESSAGE t1 " \
                      "where t1.login_name = '%s'" % loginName

                reslist = DBUtil.executeQueryList(sql)
                psw_valid_flag = reslist[0][0] # reslist.get(0).get("psw_valid_flag")

                request.session['user'] = str(user.user_id)
                request.session['username'] = user.user_name
                request.session['logintime'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                # request.session['userInfo'] = user
                request.session['psw_valid_flag'] = psw_valid_flag  # //设置密码有效时间标志位
                 # //更新上一次的登录时间和在线时间
                try:
                    sql = "update sm_usermessage t set t.last_login_date = sysdate, " \
                          "t.LAST_ONLINE_DATE = sysdate where t.login_name = '%s'"% user.login_name
                    DBUtil.executeUpdate(sql)
                except Exception, e:
                    logger.info(e)
            else:
                request.session['user'] = None
                message = u"登录失败,请重新登录"
                request.session['message'] = message
                result = "fail"
        except Exception, e:
            sql = "select t.psw_wrong_times from Sm_Usermessage t  where t.login_name = '%s'" % loginName
            try:
                psw_wrong_times = DBUtil.executeQuery_one(sql)
                if("2" == psw_wrong_times[0] ):
                    # //修改数据库字段  set is_lock=1
                    sql = "update Sm_Usermessage t set t.is_lock = 1 where t.login_name = '%s'" % loginName
                    DBUtil.executeUpdate(sql)
                else:
                    sql = "update Sm_Usermessage t set t.psw_wrong_times = %d where t.login_name  = '%s'" %(psw_wrong_times[0]+1, loginName)
                    DBUtil.executeUpdate(sql)

                logger.error("execute.ex=%s" , e)
                request.session['user'] = None
                message = u"密码输入错误" + str(psw_wrong_times[0] +1) + u"次!\n如果连续 3 次输入错误，账户将会被锁定，无法登录"
                request.session['message'] = message
                result = "fail"
            except Exception, e:
                logger.info(e)
            finally:
                pass

        if result != "fail":
            return HttpResponseRedirect('/cm/cmProductInfoAction.do') # 跳转的页面
        else:
            errors.append(u'用户名或者密码错误！！！')

    return render_to_response(request, '/login.html', {'message':message})

#登录之后跳转页
def index(request):
    print request.session.get('username', False)

    username = request.session.get('username','anybody')
    return render_to_response('index.html',{'username':username})


#注销动作
def logout(request):
    request.session['username'] = None  #删除session
    request.session['user'] = None  #删除session

    print 'log out ' + str(request.session['username']) +' ' + str(request.session['user'])
    return HttpResponseRedirect('/login/')

def loginFail(request):
    import logging
    logger = logging.getLogger(__name__)
    # logger = logging.getLogger('django')

    logger.info('aaa')
    logger.error('error occurs')
    return render_to_response('loginFail.html')


def testLogin(request):
    # try:
    #     ua = request.META['HTTP_USER_AGENT']
    # except KeyError:
    #     ua = 'unknown'
    ua = request.META.get('HTTP_USER_AGENT', 'unknown')
    return HttpResponse("Your browser is %s" % ua)

    # return render_to_response(
    #     'index.html',
    #     {'username':request.get_host(),
    #      'request':request})

def display_meta(request):
    values = request.META.items()
    values.sort()
    html = []
    for k, v in values:
        html.append('<tr><td>%s</td><td>%s</td></tr>' % (k, v))
    return HttpResponse('<table>%s</table>' % '\n'.join(html))

# def search_form(request):
#     return render_to_response('index.html')
# def search(request):
#     if 'q' in request.GET and request.GET['q']:
#         message = 'You searched for: %r' % request.GET['q']
#         return HttpResponse(message)
#     else:
#         return render_to_response('index.html', {'error': True})


def search(request):
    errors =  []
    if 'q' in request.GET:
        q = request.GET['q']
        if not q:
            errors.append('Enter a search term.')
        elif len(q) > 20:
            errors.append('Please enter at most 20 characters.')
        else:
            message = 'You searched for: %r' % request.GET['q']
            return HttpResponse(message)
    return render_to_response('index.html', {'errors': errors})


